package com.jd.sunny.java.multithreading;

/**
 * @Description:
 * @author:sunlin
 * @since:2012-12-11 11:32
 * @version:1.0.0
 */
public class TestThread implements  Runnable{

    volatile boolean isStop = false;

    private Long salary;

    public void run() {
        try {
            //线程中断只是设置中断状态，我们要自己判断决定线程是否继续运行
            while (!Thread.currentThread().isInterrupted() && !isStop){
                System.out.println("Thread is running!!this is a test program!");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println("线程在wait或sleep期间被中断了,抛出InterruptedException");
            //interrupt the thread
            //Thread.currentThread().interrupt();
        }finally {
            System.out.println("finally,do some clean if required");
        }
    }

    public static void main(String[]args){
        TestThread runnable = new TestThread();
        Thread thread = new Thread(runnable);

        /**
         * Set daemon thread
         * must invoke before start
         * daemon thread never should have access fixed resources because it may interupt anytime
         */
        thread.setDaemon(true);

        thread.start();

        //等待指定的线程结束
        try {
            thread.join(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }



        /**
         * Get thread state
         *
         * public static enum Thread.Stateextends Enum<Thread.State>
         *
         * NEW至今尚未启动的线程处于这种状态。
         *RUNNABLE正在 Java 虚拟机中执行的线程处于这种状态
         *BLOCKED受阻塞并等待某个监视器锁的线程处于这种状态
         *WAITING无限期地等待另一个线程来执行某一特定操作的线程处于这种状态。
         *TIMED_WAITING等待另一个线程来执行取决于指定等待时间的操作的线程处于这种状态。
         *TERMINATED已退出的线程处于这种状态。
         *
         */

        Thread.State state =  thread.getState();
        System.out.println(state);

        /**
         * yield()
         */
        Thread.yield();

        /**
         * Set Priority
         *public final void setPriority(int newPriority)
         *newPriority(1-10)
         *
         */
        thread.setPriority(8);

        /**
         *未捕获异常处理
         */
        Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t, Throwable e) {
                e.printStackTrace();
            }
        };

        Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
        thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);


        /**
         * 同步
         */
        














    }


    public Long getSalary() {
        return salary;
    }

    public void setSalary(Long salary) {
        this.salary = salary;
    }
}
